﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace VSM
{
    public partial class ReservationSheet : System.Web.UI.Page
    {

        private static DataTable dtContents;
        private static GeneralFunctions GF = null;
        private static string dbType;
        private static int ServiceID = 12;//-1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            
            if (!IsPostBack)
            {
                dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
               

                ServiceID = Request.QueryString["ServiceID"] == null ? -1 : Int32.Parse(Request.QueryString["ServiceID"]);
                if (ServiceID == -1)
                {
                    generateNewJobID();
                    loadDefaultData();
                    dtContents = new DataTable();
                    
                    grvPO.DataSource = dtContents;
                    grvPO.DataBind();
                }
                else {
                    loadDataByServiceID();

                }
                
                // Add code check security here
                
                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    //txtDealerCode.ReadOnly = true;
                    //txtDealerCode.BackColor = ColorTranslator.FromHtml("#E6E6E6");
                    //hf_GeneralID.Value = Request.QueryString["id"];
                    //btnUpdate.Text = "Update Dealer";
                    if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0)
                    {
                        
                    }
                }
                else if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0) // Add new dealer
                {
                    //btnUpdate.Text = "Add Dealer";
                    //DealerCode.Value = "";
                }
            }
        }

        private void generateNewJobID()
        {
            Services sv = new Services();
            string sql = "select RIGHT('000' + CAST(count(*) + 1 as nvarchar(5)), 3) as GreatestNum from U_GeneralService where MONTH(ServiceDate) = 5 and YEAR(ServiceDate) = 2014 and DealerCode = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "'";
            DataSet dsJobID = sv.ExecuteQuery(dbType, sql);
            if (dsJobID.Tables[0].Rows.Count > 0) {
                DateTime curr = DateTime.Now;
                txt_JobID.Text = dsJobID.Tables[0].Rows[0]["GreatestNum"].ToString() + "/" + curr.ToString("MMyy");
            }
            
        }

        private void loadDefaultData() {
            txt_Odometer.Text = "0";
            DateTime currDate = DateTime.Now;
            txtDate.Text = currDate.ToString("dd/MM/yyyy");
            Services svc = new Services();
            DataSet ds =  svc.ExecuteQuery("VSM", "select UserName from tbl_MasterUsers where ID_User = '" + Session[Utils.AppConstants.ID_User] + "'" );
            if (ds.Tables[0].Rows.Count > 0) {
                txt_Receptionist.Text = ds.Tables[0].Rows[0]["UserName"].ToString();
            }

            DataSet dsPackage = svc.ExecuteQuery("VSM", "select -1 as PackageID, 'Choose Package' as PackageName Union All select PackageID, PackageName from U_Package");
            ddl_Package.DataSource = dsPackage.Tables[0];
            ddl_Package.DataTextField = "PackageName";
            ddl_Package.DataValueField = "PackageID";
            ddl_Package.DataBind();
        }

        

        private string FormatDate(string dateIn) {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");
            
        }
        
        private void loadDataByServiceID() {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery(dbType, "select * from U_GeneralService where GeneralID = " + ServiceID.ToString());
            hf_GeneralID.Value = ServiceID.ToString();
            if (ds.Tables[0].Rows.Count > 0) {
                
                DataRow dr = ds.Tables[0].Rows[0];
                txt_Receptionist.Text = dr["Receptionist"].ToString();

                txt_Odometer.Text = dr["Odometer"].ToString();
                
                hf_CustomerCode.Value = dr["CustomerCode"].ToString();
                hf_VehicleID.Value = dr["VehicleCode"].ToString();
                loadCustomer();
                loadVehicle();
                //loadDetail();

            }
        }
        private void loadCustomer() {
            MasterData masterDataWS = new MasterData();
            DataSet ds = masterDataWS.GetCustomerByCode("VSM", hf_CustomerCode.Value);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CardName"].ToString();
                txt_OtherName.Text = ds.Tables[0].Rows[0]["CardFName"].ToString();
                txt_Address.Text = ds.Tables[0].Rows[0]["Address"].ToString();
                txt_Tel.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
                txt_TaxCode.Text = ds.Tables[0].Rows[0]["LicTradNum"].ToString();
                txt_ContactPerson.Text = ds.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                txt_PhoneContact.Text = ds.Tables[0].Rows[0]["U_ContactPhone"].ToString();
            }
        }

        private void loadVehicle() {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery(dbType, "select * from U_ServiceVehicle where VehicleID = " + hf_VehicleID.Value);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
            }
        }

        private void loadDetail() {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery(dbType, "select * from U_GeneralServiceDetail where GeneralID = " + ServiceID.ToString());
            dtContents = ds.Tables[0];
            grvPO.DataSource = dtContents;
            grvPO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
            if (fu_ImportExcel.HasFile) { 
                
            }
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
          
            //txtPONo.Text = "PO-" + "003/0414";
            //txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
      
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //if (txtDealerCode.Text == "")
            //{
            //    Session["errorMessage"] = "Missing Dealer Code";
            //    Session["requestXML"] = "";
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Dealer Code','');", true);
            //}
            /*
            String requestXML = _collectData();
            Transaction ts = new Transaction();

            DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.BUSINESS_PARTNER).ToString(), txtDealerCode.Text, !string.IsNullOrEmpty(DealerCode.Value), Utils.AppConstants.VSM
            );

            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
       
             */
        }
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               // Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
               // this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
            //UpdatePrice();
        }
        private String _collectData()
        {
            try
            {
                DataTable dt = new DataTable("OCRD");
                dt.Columns.Add("CardCode");
                dt.Columns.Add("CardName");
                dt.Columns.Add("Address");
                dt.Columns.Add("LicTradNum");
                dt.Columns.Add("Phone1");
                dt.Columns.Add("Phone2");
                dt.Columns.Add("CardType");
                dt.Columns.Add("GroupCode");
                dt.Columns.Add("Cellular");
                dt.Columns.Add("Fax");
                dt.Columns.Add("E_Mail");
                
                DataRow dr = dt.NewRow();

                //dr["CardCode"] = txtDealerCode.Text;
                //dr["CardName"] = txtDealerName.Text;
                //dr["Address"] = txtAddress.Text;
                //dr["LicTradNum"] = txtTaxCode.Text;
                //dr["Phone1"] = txtTel1.Text;
                //dr["Phone2"] = txtTel2.Text;
                //dr["CardType"] = "C";
                //dr["GroupCode"] = "104";
                //dr["Cellular"] = txtMobilePhone.Text;
                //dr["Fax"] = txtFax.Text;
                //dr["E_Mail"] = txtEmail.Text;

                //dr["U_UserID"] = User.Identity.Name;
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");

                dt.Rows.Add(dr);

                ds.Tables.Add(dt.Copy());
                return objInfo.ToXMLStringFromDS(((ulong)DocType.BUSINESS_PARTNER).ToString(), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }
 

        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {

            /*this.txtVendorCode.Text = "";
            this.txtVendorName.Text = "";
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnUpdate.Enabled = false;*/
        }

       
      
        protected void TextBox_Change(object sender, EventArgs e)
        {
            // string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            TextBox tb = (TextBox)sender;
            string ItemCode = "'" + tb.Text + "'";
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            int rowNo = Int32.Parse( lblNo.Text) -1;
            int index = 0;
            foreach (DataRow dr in dtContents.Rows) {
                if (rowNo == index) {

                    MasterData mt = new MasterData();
                    DataSet dsItem = mt.GetItemsByItemCodeList(dbType, Utils.AppConstants.ID_Dealer, ItemCode);
                    
                    if (dsItem.Tables[0].Rows.Count == 1) {
                        dr["ItemCode"] = dsItem.Tables[0].Rows[0]["ItemCode"];
                        dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
                        dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
                        dr["Quantity"] = 1;
                        dr["Price"] = 10000;//dsItem.Tables[0].Rows[0]["Price"];
                        dr["VAT"] = 10;//dsItem.Tables[0].Rows[0]["VAT"];
                        dr["DiscPrcnt"] = 10;//dsItem.Tables[0].Rows[0]["Discount"];
                        dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];
                        grvPO.DataSource = dtContents;
                        grvPO.DataBind();

                        this.lblError.Visible = false;
                        break;
                    }
                    else if (dsItem.Tables[0].Rows.Count > 1)
                    {
                        string msg = "Available parts: ";
                        foreach (DataRow drItem in dsItem.Tables[0].Rows)
                        {
                            msg += "";
                        }
                        this.lblError.Text = msg;
                        this.lblError.Visible = true;
                        break;
                    }
                    else { //=0
                        this.lblError.Text = "There is no part with code [" + tb.Text + "] available ";
                        this.lblError.Visible = true;
                    }
                    
                }
                index++;
            }

            
           

            //ListViewItem lvi = e.Item;

            //Label lblNo = (Label)lvi.FindControl("lblNo");
            //foreach (DataRow row in dtContents.Rows)
            //{
            //    if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
            //    {
            //        Label lx = (Label)lvi.FindControl("ItemName");
            //        lx.Text = "Ha ha ha ha";

            //        //row["ItemCode"] = ((Label)lvi.FindControl("lblCode")).Text;
            //        //row["Dscription"] = ((Label)lvi.FindControl("lblDescription")).Text;
            //        //row["Quantity"] = ((TextBox)lvi.FindControl("txtQuantity")).Text;
            //        break;
            //    }
            //}
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            dtContents.Rows.Add(dtContents.Rows.Count, "", "", "", "", "", "", "", "", "");
            this.grvPO.DataSource = dtContents;
            this.grvPO.DataBind();
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
                //if (this.hdnStatus.Value == "C")
                //{
                //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
                //    txtQuantity.Enabled = false;
                //}
            }
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
                //this.lblDocumentTotal.Text = string.Format("{0:C}", Math.Round(documentTotal, 2));
                //this.lblTaxAmount.Text = string.Format("{0:C}", Math.Round(gstTotal, 2));
                //this.lblSubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                int rowNo = Int32.Parse(lblNo.Text) - 1;
               
                foreach (DataRow dr in dtContents.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString())) {
                        dr.Delete();
                        break;
                    }
                }
                //reload number
                int index = 0;
                foreach (DataRow dr in dtContents.Rows)
                    dr["No"] = ++index;

                grvPO.DataSource = dtContents;
                grvPO.DataBind();
           

                /*
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
                 * */
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
              
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");

        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
           
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPO.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["POR1Table"]);
        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPO.EditIndex = -1;
            BindData((DataTable)Session["POR1Table"]);
        }

        private void GetPrice(DataRow r)
        {
            try
            {
                /*
                DataSet ds = GetDataItem(DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
                 * */
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPO.EditIndex = -1;

                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btn_ImportPackage_Click(object sender, EventArgs e)
        {
            string selectedPackage = ddl_Package.SelectedValue.ToString();
            if (selectedPackage != "-1")
            {
                Services sv = new Services();
                DataSet ds =  sv.ExecuteQuery("VSM", "select PacDetID, ItemCode, Quantity from  U_PackageDetail where PackageID = " + selectedPackage);
                if (ds.Tables[0].Rows.Count > 0) {
                    foreach (DataRow dr in ds.Tables[0].Rows) {
                        string ItemCode = dr["ItemCode"].ToString();
                        double qty = Double.Parse( dr["Quantity"].ToString());
                        dtContents.Rows.Add(GetLineInfo(ItemCode, qty));
                    }
                    grvPO.DataSource = dtContents;
                    grvPO.DataBind();
                }
            }

        }


        private DataRow GetLineInfo(string ItemCode, double qty)
        {
            DataRow dr = dtContents.NewRow();
            GetDefault defaultWS = new GetDefault();
            MasterData mt = new MasterData();
            DataSet dsItem = mt.GetItemsByItemCodeList(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), "'"+ItemCode+"'");

            DataSet defaultInfo = null; // defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                         //"VS", ItemCode, qty, DateTime.Now);

            dr["ItemCode"] = ItemCode;
            dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
            dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
            dr["Quantity"] = qty;
            dr["Price"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
            dr["VAT"] = 10;
            dr["DiscPrcnt"] = defaultInfo.Tables[0].Rows[0]["Discount"];
            dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];

            return dr;
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ServiceDate");
            dt.Columns.Add("JobID");
            dt.Columns.Add("Receptionist");
            dt.Columns.Add("AdviserCode");
            dt.Columns.Add("TechnicianCode");
            dt.Columns.Add("JobKind");
            dt.Columns.Add("Payment");
            dt.Columns.Add("DateIn");
            dt.Columns.Add("TimeIn");
            dt.Columns.Add("ExpDelivery");
            dt.Columns.Add("ExpTime");
            dt.Columns.Add("StartDate");
            dt.Columns.Add("StartTime");
            dt.Columns.Add("FinishDate");
            dt.Columns.Add("FinishTime");
            dt.Columns.Add("ActualDelivery");
            dt.Columns.Add("ActualDeliveryTime");
            dt.Columns.Add("CustomerRequest");
            dt.Columns.Add("Notice");
            dt.Columns.Add("CustomerCode");
            dt.Columns.Add("VehicleCode");
            dt.Columns.Add("Odometer");
            dt.Columns.Add("DealerCode");
            dt.Columns.Add("GeneralID");

            DataRow dr = dt.NewRow();
            if (txtDate.Text.Trim() == "")
                dr["ServiceDate"] = DBNull.Value;
            else
                dr["ServiceDate"] = Utils.AppConstants.ConvertToDate(txtDate.Text.Trim());

            //dr["JobID"] = txt_JobID.Text;
            //dr["Receptionist"] = txt_Receptionist.Text;
            //dr["AdviserCode"] = ddl_Adviser.SelectedValue;
            //dr["TechnicianCode"] = ddl_Technician.SelectedValue;
            //dr["JobKind"] = ddl_JobKind.SelectedValue;
            //dr["Payment"] = ddl_Payment.SelectedValue;
            //if (txt_DateIn.Text.Trim() == "")
            //    dr["DateIn"] = DBNull.Value;
            //else
            //    dr["DateIn"] = Utils.AppConstants.ConvertToDate(txt_DateIn.Text.Trim());

            //dr["TimeIn"] = txt_TimeIn.Text;
            //if (txt_ExpDate.Text.Trim() == "")
            //    dr["ExpDelivery"] = DBNull.Value;
            //else
            //    dr["ExpDelivery"] = Utils.AppConstants.ConvertToDate(txt_ExpDate.Text.Trim());

            //dr["ExpTime"] = txt_ExpTime.Text;
            //if (txt_StartDate.Text.Trim() == "")
            //    dr["StartDate"] = DBNull.Value;
            //else
            //    dr["StartDate"] = Utils.AppConstants.ConvertToDate(txt_StartDate.Text.Trim());
            //dr["StartTime"] = txt_StartTime.Text;

            //if (txt_FinishDate.Text.Trim() == "")
            //    dr["FinishDate"] = DBNull.Value;
            //else
            //    dr["FinishDate"] = Utils.AppConstants.ConvertToDate(txt_FinishDate.Text.Trim());
            //dr["FinishTime"] = txt_FinishTime.Text;

            //if (txt_ActualDate.Text.Trim() == "")
            //    dr["ActualDelivery"] = DBNull.Value;
            //else
            //    dr["ActualDelivery"] = Utils.AppConstants.ConvertToDate(txt_ActualDate.Text.Trim());
            //dr["ActualDeliveryTime"] = txt_ActualTime.Text;
            //dr["CustomerRequest"] = txt_CustomerRequest.Text;
            //dr["Notice"] = txt_Notice.Text;
            //dr["CustomerCode"] = hf_CustomerCode.Value;
            //dr["VehicleCode"] = hf_VehicleID.Value;
            //dr["Odometer"] = txt_Odometer.Text;
            //dr["DealerCode"] = Session[Utils.AppConstants.ID_Dealer].ToString();
            //dr["GeneralID"] = ServiceID;

            Services svc = new Services();
            dt.Rows.Add(dr);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            if (ServiceID == -1) //add new
            {
               
                ServiceID = svc.InsertGeneralService(dbType, ds);
                if (ServiceID != -1)
                {
                    DataSet dsDetail = new DataSet();
                    DataTable dtDetail = new DataTable();
                    dtDetail.Columns.Add("GeneralID");
                    dtDetail.Columns.Add("ItemCode");
                    dtDetail.Columns.Add("ItemName");
                    dtDetail.Columns.Add("FrgnName");
                    dtDetail.Columns.Add("Quantity");
                    dtDetail.Columns.Add("Price");
                    dtDetail.Columns.Add("VAT");
                    dtDetail.Columns.Add("DiscPrcnt");
                    dtDetail.Columns.Add("Stock");

                    foreach (DataRow drDetail in dtContents.Rows) {
                        dsDetail.Tables.Clear();
                        DataRow toAdd = dtDetail.NewRow();
                        toAdd["GeneralID"] = ServiceID;
                        toAdd["ItemCode"] = drDetail["ItemCode"];
                        toAdd["ItemName"] = drDetail["ItemName"];
                        toAdd["FrgnName"] = drDetail["FrgnName"];
                        toAdd["Quantity"] = drDetail["Quantity"];
                        toAdd["Price"] = drDetail["Price"];
                        toAdd["VAT"] = drDetail["VAT"];
                        toAdd["DiscPrcnt"] = drDetail["DiscPrcnt"];
                        toAdd["Stock"] = drDetail["Stock"];
                        dtDetail.Rows.Clear();
                        dtDetail.Rows.Add(toAdd);
                        dsDetail.Tables.Add(dtDetail);
                        svc.InsertGeneralServiceDetail(dbType, dsDetail);
                    }
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Add New] Operation complete sucessful!" + "','');", true);
                   
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Add New] ! Operation Failed" + "','');", true);
                }
            }
            else { //update
                int count = svc.UpdateGeneralService(dbType, ds);
                if (count != -1)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Update] Operation complete sucessful!" + "','');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Update] Operation failed!" + "','');", true);
                }
            }
            //            ([JobID],[Receptionist],[AdviserCode],[TechnicianCode],[JobKind],[Payment],[DateIn]
            //,[TimeIn],[ExpDelivery],[ExpTime],[StartDate],[StartTime],[FinishDate],[FinishTime]
            //,[ActualDelivery],[ActualDeliveryTime],[CustomerRequest],[Notice],[CustomerCode],[VehicleCode])
        }

        
    }

}